package durst.data.dao.impl;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;

import durst.data.Account;

public class AccountDao<T, ID> extends BaseDaoImpl<T, ID> {
	@SuppressWarnings("unchecked")
	public AccountDao(ConnectionSource connectionSource)
			throws SQLException {
		super(connectionSource, (Class<T>)Account.class);
	}

	public AccountDao(ConnectionSource connectionSource,
			DatabaseTableConfig<T> tableConfig) throws SQLException {
		super(connectionSource, tableConfig);
	}

	public T queryByUsername(String username) throws SQLException {
		SelectArg user = new SelectArg();
		user.setValue(username);
		
		List<T> res = queryBuilder().where().eq(Account.USERNAME, user).query();
		
		assert (res.size() <= 1);

		return res.size() == 1 ? res.get(0) : null;
	}

	public List<T> queryByUsernameOrEmail(String username, String email)
			throws SQLException {
		SelectArg user = new SelectArg();
		user.setValue(username);
		SelectArg em = new SelectArg();
		em.setValue(email);
		
		if (username != null && email != null)
			return queryBuilder().where().eq(Account.USERNAME, user).or().eq(Account.EMAIL, em)
				.query();
		else if (username != null) 
			return queryBuilder().where().eq(Account.USERNAME, user).query();
		else if (email != null) 
			return queryBuilder().where().eq(Account.EMAIL, em).query();
		else
			return new LinkedList<T>();
	}
}
